#include "mythreadpool.h"
#include <qdebug.h>
#include <QRegularExpression>
#include <QFile>
#include <QString>
#include <QList>
#include <QDebug>
#include <QElapsedTimer>

void parseLogLineFast(const QString &line, QStringList& lists)
{
    lists = line.split("][");

    if(lists.size() >= 7)
    {
        lists[0].remove(0,1);
        int pos = lists[6].indexOf("]");
        QString tail  = lists[6].mid(pos + 1);
        lists[6].remove(pos,lists[6].length()- pos);
        lists.append(tail);
    }
}


void LoadFileTask::run()
{
    qDebug()<<__func__<<" begin "<<m_notifier->get_attr();

    QString filePath = m_notifier->get_attr();
    QFile file(filePath);
    QStringList groups;
    QVector<LogEntry> entries;
    QString line;
    int index = 0;

    QElapsedTimer timer;
    timer.start();

    do{
        emit m_notifier->taskFinished(TASK_BEGIN,"begin");

        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qWarning() << "无法打开文件：" << filePath;
            emit m_notifier->taskFinished(TASK_RUNNING,"open file failed!!");
            break;
        }

        QTextStream in(&file);
        while (!in.atEnd()) {
            line = in.readLine();

            groups.clear();

            parseLogLineFast(line,groups);

            if(groups.size() != 8)
            {
                qWarning()<<"匹配失败 ："<<line;
                emit m_notifier->taskFinished(TASK_RUNNING,"match line failed!!");
                continue;
            }

            LogEntry entry;
            entry.serialNumber   = groups[0];   // 序号
            entry.level          = groups[6];   // 日志级别
            entry.content        = groups[7];   // 日志内容
            entry.fileName       = groups[4];   // 文件名
            entry.threadId       = groups[3];   // 线程ID
            entry.timestamp      = groups[1] + " " + groups[2];   // 日期
            entry.lineNumber     = groups[5];   // 行号

            entries.push_back(entry);

//            if(index % 1000 == 0)
//            {
//                emit m_notifier->taskLineInfo(entries);
//                entries.clear();
//            }
//            index++;
        }

        emit m_notifier->taskLineInfo(entries);

        file.close();
    }while(0);

    qint64 elapsedMs = timer.elapsed(); // 获取已过去的时间（毫秒）
    QString info = QString("文件[ %1] 读取完成,耗时[%2]ms").arg(file.fileName()).arg(elapsedMs);
    emit m_notifier->taskFinished(TASK_END,info);

    qDebug()<<__func__<<" end "<<m_notifier->get_attr();
}
